/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.tms.entity.TruckOwner;
import com.jeeplus.modules.tms.mapper.TruckOwnerMapper;
import com.jeeplus.modules.tms.entity.Trucks;
import com.jeeplus.modules.tms.mapper.TrucksMapper;

/**
 * 车辆Service
 * @author dhw
 * @version 2018-01-17
 */
@Service
@Transactional(readOnly = true)
public class TruckOwnerService extends CrudService<TruckOwnerMapper, TruckOwner> {

	@Autowired
	private TrucksMapper trucksMapper;
	
	public TruckOwner get(String id) {
		TruckOwner truckOwner = super.get(id);
		truckOwner.setTrucksList(trucksMapper.findList(new Trucks(truckOwner)));
		return truckOwner;
	}
	
	public List<TruckOwner> findList(TruckOwner truckOwner) {
		return super.findList(truckOwner);
	}
	
	public Page<TruckOwner> findPage(Page<TruckOwner> page, TruckOwner truckOwner) {
		return super.findPage(page, truckOwner);
	}
	
	@Transactional(readOnly = false)
	public void save(TruckOwner truckOwner) {
		super.save(truckOwner);
		for (Trucks trucks : truckOwner.getTrucksList()){
			if (trucks.getId() == null){
				continue;
			}
			if (Trucks.DEL_FLAG_NORMAL.equals(trucks.getDelFlag())){
				if (StringUtils.isBlank(trucks.getId())){
					trucks.setTruckOwner(truckOwner);
					trucks.preInsert();
					trucksMapper.insert(trucks);
				}else{
					trucks.preUpdate();
					trucksMapper.update(trucks);
				}
			}else{
				trucksMapper.delete(trucks);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(TruckOwner truckOwner) {
		super.delete(truckOwner);
		trucksMapper.delete(new Trucks(truckOwner));
	}

	@Transactional(readOnly = false)
	public void saveTrucks(Trucks trucks) {
		if (trucks.getIsNewRecord()){
			trucks.preInsert();
			trucksMapper.insert(trucks);
		}else{
			trucks.preUpdate();
			trucksMapper.update(trucks);
		}
	}
}